package com.uxwine.alarm.main;

import java.util.Calendar;

public class Timer {
	
	public static final int BASE	= 0;
	public static final int YEAR 	= BASE + 0;
	public static final int MONTH 	= BASE + 1;
	public static final int DATE	= BASE + 2;
	public static final int HOUR	= BASE + 3;
	public static final int MINITE	= BASE + 4;
	
	private int[] values;
	
	public Timer()
	{
		values = new int[5];
	}
	
	public void reset()
	{
		init();
	}
	
	public void init()
	{
		init(Calendar.getInstance());		
	}
	
	public void init(long time)
	{
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(time);
		init(c);
	}
	
	public void init(Calendar c)
	{
		values[YEAR] = c.get(Calendar.YEAR);
		values[MONTH] = c.get(Calendar.MONTH) + 1;
		values[DATE] = c.get(Calendar.DATE);
		values[HOUR] = c.get(Calendar.HOUR_OF_DAY);
		values[MINITE] = c.get(Calendar.MINUTE);
	}
	
	public long getTime()
	{
		Calendar c = Calendar.getInstance();
		c.set(values[YEAR], values[MONTH] - 1, values[DATE], values[HOUR], values[MINITE], 0);
		return c.getTimeInMillis();
	}
	
	public int get(int key)
	{
		return values[key];
	}
	
	public void set(int key, int value)
	{
		switch(key)
		{
		case YEAR: 
			values[key] = value;break;
		case MONTH:
			if(value > 0 && value <= 12)
			{
				values[key] = value;
				if(value == 2)
				{
					int m = getDays(values[YEAR], value);
					if(values[DATE] > m)
						values[DATE] = m;					
				}
			}
			break;
		case DATE:
		{
			int m = getDays(values[YEAR], values[MONTH]);
			if(value > 0 && value < m)
				values[key] = value;
			break;
		}
		case HOUR:
		{
			if(value >= 0 && value < 24)
				values[key] = value;
			break;
		}
		case MINITE:
			if(value >= 0 && value < 60)
				values[key] = value;
			break;
		}
	}
	
	public int getDaysOfMonth()
	{
		return getDays(values[YEAR], values[MONTH]);
	}
	
    public static boolean isLeap(int year)  
    {  
        if (((year % 100 == 0) && year % 400 == 0) || ((year % 100 != 0) && year % 4 == 0))  
            return true;  
        else  
            return false;  
    }  
  
    public int getDays(int year, int month)  
    {  
        int days = 0;  
        switch (month)  
        {  
            case 1:  
            case 3:  
            case 5:  
            case 7:  
            case 8:  
            case 10:  
            case 12:  
                days = 31;  
                break;  
            case 4:  
            case 6:  
            case 9:  
            case 11:  
                days = 30;  
                break;  
            case 2:  
                days = isLeap(year) ? 29 : 28;  
                break;  
            default:   
                break;  
        }  
        return days;  
    }  
}
